"""
设备模拟器
用于测试目的的各种工业设备模拟器
"""

import threading
import time
import random
import logging
from typing import Dict, Any

class ModbusSimulator:
    """Modbus设备模拟器"""
    
    def __init__(self, host='127.0.0.1', port=5020):
        self.host = host
        self.port = port
        self.running = False
        self.data = {}
        self.logger = logging.getLogger(self.__class__.__name__)
    
    def start(self):
        """启动模拟器"""
        self.running = True
        self.logger.info(f"Modbus模拟器启动: {self.host}:{self.port}")
        
        # 初始化模拟数据
        self.data = {
            40001: 1200,  # 电机转速
            40002: 75.5,  # 温度
            40003: 1500   # 生产计数
        }
    
    def stop(self):
        """停止模拟器"""
        self.running = False
        self.logger.info("Modbus模拟器已停止")
    
    def update_data(self):
        """更新模拟数据"""
        if self.running:
            self.data[40001] = random.randint(1000, 1500)  # 电机转速变化
            self.data[40002] = round(random.uniform(70, 85), 1)  # 温度变化
            self.data[40003] += random.randint(1, 5)  # 生产计数增加

class S7Simulator:
    """S7 PLC模拟器"""
    
    def __init__(self, host='127.0.0.1'):
        self.host = host
        self.running = False
        self.data = {}
        self.logger = logging.getLogger(self.__class__.__name__)
    
    def start(self):
        """启动模拟器"""
        self.running = True
        self.logger.info(f"S7模拟器启动: {self.host}")
        
        # 初始化S7数据
        self.data = {
            'DB1.DBD10': 15.5,  # 传送带速度
            'M0.0': True        # 阀门状态
        }
    
    def stop(self):
        """停止模拟器"""
        self.running = False
        self.logger.info("S7模拟器已停止")

class MQTTSimulator:
    """MQTT设备模拟器"""
    
    def __init__(self, broker='127.0.0.1', port=1883):
        self.broker = broker
        self.port = port
        self.running = False
        self.logger = logging.getLogger(self.__class__.__name__)
    
    def start(self):
        """启动模拟器"""
        self.running = True
        self.logger.info(f"MQTT模拟器启动: {self.broker}:{self.port}")
    
    def stop(self):
        """停止模拟器"""
        self.running = False
        self.logger.info("MQTT模拟器已停止")

class OPCUASimulator:
    """OPC UA服务器模拟器"""
    
    def __init__(self, endpoint='opc.tcp://127.0.0.1:4840'):
        self.endpoint = endpoint
        self.running = False
        self.data = {}
        self.logger = logging.getLogger(self.__class__.__name__)
    
    def start(self):
        """启动模拟器"""
        self.running = True
        self.logger.info(f"OPC UA模拟器启动: {self.endpoint}")
        
        # 初始化OPC UA数据
        self.data = {
            'ns=2;i=2': 3.2  # 储罐液位
        }
    
    def stop(self):
        """停止模拟器"""
        self.running = False
        self.logger.info("OPC UA模拟器已停止")

class SimulatorManager:
    """模拟器管理器"""
    
    def __init__(self):
        self.simulators = {
            'modbus': ModbusSimulator(),
            's7': S7Simulator(),
            'mqtt': MQTTSimulator(),
            'opcua': OPCUASimulator()
        }
        self.logger = logging.getLogger(self.__class__.__name__)
    
    def start_all(self):
        """启动所有模拟器"""
        for name, simulator in self.simulators.items():
            try:
                simulator.start()
                self.logger.info(f"启动{name}模拟器成功")
            except Exception as e:
                self.logger.error(f"启动{name}模拟器失败: {e}")
    
    def stop_all(self):
        """停止所有模拟器"""
        for name, simulator in self.simulators.items():
            try:
                simulator.stop()
                self.logger.info(f"停止{name}模拟器成功")
            except Exception as e:
                self.logger.error(f"停止{name}模拟器失败: {e}")
    
    def start_simulator(self, protocol: str):
        """启动指定协议的模拟器"""
        if protocol in self.simulators:
            self.simulators[protocol].start()
            return True
        return False
    
    def stop_simulator(self, protocol: str):
        """停止指定协议的模拟器"""
        if protocol in self.simulators:
            self.simulators[protocol].stop()
            return True
        return False

# 用于测试的简单模拟器启动函数
def run_test_simulators():
    """运行测试模拟器"""
    manager = SimulatorManager()
    
    try:
        print("🚀 启动设备模拟器...")
        manager.start_all()
        
        print("✅ 模拟器运行中，按Ctrl+C停止")
        while True:
            time.sleep(1)
            
    except KeyboardInterrupt:
        print("\n🛑 停止设备模拟器...")
        manager.stop_all()
        print("✅ 设备模拟器已停止")

if __name__ == '__main__':
    # 设置日志
    logging.basicConfig(level=logging.INFO)
    run_test_simulators() 